package org.jeecg.modules.online.low.aspect;


import org.apache.commons.lang.StringUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.online.low.constant.LowAppConst;
import org.jeecg.modules.online.low.util.ParameterRequestWrapper;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * LowApp的过滤器
 *
 * @author sunjianlei
 */
@Component("lowAppFilter")
public class LowAppFilter extends OncePerRequestFilter {

    /**
     * 列表过滤路径
     */
    private static final List<String> LIST_PATHS = new ArrayList<>();

    static {
        LIST_PATHS.add("/desform/list");
        LIST_PATHS.add("/online/cgform/head/list");
        LIST_PATHS.add("/online/cgreport/head/list");
        LIST_PATHS.add("/online/graphreport/head/list");
    }

    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        if (this.pathContains(LIST_PATHS, request)) {
            this.doFilterList(request, response, filterChain);
        } else {
            filterChain.doFilter(request, response);
        }
    }

    /**
     * 处理数据列表，用于隔离app数据
     */
    private void doFilterList(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        Map<String, Object> params = new HashMap<>();
        // 判断Header中是否包含 lowAppId
        String lowAppId = request.getHeader(LowAppConst.X_LOW_APP_ID);
        if (StringUtil.isNotEmpty(lowAppId)) {
            params.put(LowAppConst.FIELD_LOW_APP_ID, lowAppId);
            // 通过 ParameterRequestWrapper 扩展请求参数
            ParameterRequestWrapper wrapper = new ParameterRequestWrapper(request, params);
            filterChain.doFilter(wrapper, response);
        } else {
            filterChain.doFilter(request, response);
        }
    }

    /**
     * 判断list中是否包含url
     *
     * @param list
     * @param request
     * @return
     */
    private boolean pathContains(List<String> list, HttpServletRequest request) {
        String URI = request.getRequestURI();
        return list.stream().anyMatch(URI::contains);
    }

}
